/**
 * 参数 load_url: 加载图片列表 url
 * 参数 del_url: 删除图片url；
 * 参数 duration： 动画延时，单位毫秒
 * 参数 shadowClose: 点击阴影是否关闭
 * 参数 headers : 设置headers参数
 * 参数 method : ajax加载图片的 method 方式
 * 参数 pagesize ： 每页加载图片数目
 * 参数 max_select_count: 最多选中图片数量
 *
 * ajax 装载图片，返回结果为json，格式如下：
 *  code ==0: 正确，其他，则异常
 * { code: 0,msg: '消息说明' , data:{ count: 0 , rows:[{ 'imgId':'','imgUrl':'','imgTitle':'' },{} ] } }
 */

class PbFilebox {
    constructor(opt) {
        this.option = opt==null ? {}:opt ;
        this.option.duration = (this.option.duration == null ? 500: this.option.duration );
        this.option.shadowClose = (this.option.shadowClose == null ? true: this.option.shadowClose );
        this.option.method = (this.option.method == null||this.option.method==''  ? 'POST': this.option.method );
        this.option.pagesize = (this.option.pagesize == null ? 21: this.option.pagesize );
        this.option.max_select_count = (this.option.max_select_count == null ? 1: this.option.max_select_count );

        // 每个宽度和高度
        this.liwidth = 160;
        this.liheight = 160;
        this.ulpadding2 = 40;
        this.imgcount = 0;
        this.pagecount = 0;
        this.pagenumb = 1;

        this.selected =[];
    }

    show(){
        let _this = this;
        this._build();
        this._loadImgs();
        this._bindEvent();
        $('.pb-filebox-shadow,.pb-filebox').fadeIn({ duration: _this.option.duration });
    }
    hide(){
        let _this = this;
        $('.pb-filebox-shadow,.pb-filebox').fadeOut({ duration: _this.option.duration });
        _this._clearImgs();
    }
    addImg(imgid,imgUrl,imgTitle){
        let _this = this;
        if($('.pb-filebox-ul-imgs')[0] == null){
            return;
        }
        let lihtml = ` <li class="pb-filebox-li-img" data-imgid="${imgid}" data-imgurl="${imgUrl}" data-imgtitle="${imgTitle}"> 
            <div class="pb-filebox-imgbox"><img class="pb-filebox-img-item" src="${imgUrl}" title="${imgTitle}"></div>
            <div class="pb-filebox-imgtitle"><div class="pb-filebox-imgtitle-text" title="${imgTitle}"> ${imgTitle}</div> </div>
            <div class='pb-filebox-li-imgbox-okbtn'></div> </li>`;

        $('.pb-filebox-ul-imgs li.pb-cl').before(lihtml);
        let liItem = $('.pb-filebox-ul-imgs li.pb-filebox-li-img').last();

        _this._refreshImgBoxWidth();

        liItem.on('click',function(e) {
            let liItem = e.currentTarget;

            // 获取当前liItem的 imgId,imgUrl,imgTitle
            let imgId = $(liItem).attr('data-imgid');
            let imgUrl = $(liItem).attr('data-imgurl');
            let imgTitle = $(liItem).attr('data-imgtitle');

            let obj = {'imgId': imgId, 'imgUrl': imgUrl, 'imgTitle': imgTitle};

            _this._toggleImg(obj);
            _this._refreshSelectStatus();
            _this._showSelectNumb();
        });

    }
    _toggleImg(obj){
        for(var i=0;i<this.selected.length;i++){
            if(this.selected[i].imgId == obj.imgId ){
                this._removeSelectImg(obj);
                return;
            }
        }
        this._addSelectImg(obj);
    }
    _addSelectImg(obj){
        for(var i=0;i<this.selected.length;i++){
            if(this.selected[i].imgId == obj.imgId ){
                return;
            }
        }
        if(this.selected.length>=this.option.max_select_count){
           this.selected.splice(0, this.selected.length - this.option.max_select_count + 1);
        }
        this.selected.push(obj);
    }
    _removeSelectImg(obj){
        for(var i=0;i<this.selected.length;i++){
            if(this.selected[i].imgId == obj.imgId ){
                this.selected.splice(i,1);
            }
        }
    }
    _refreshSelectStatus(){
        let _this = this;
        $('.pb-filebox-shadow li.pb-filebox-li-img').each(function () {
            let imgId = $(this).attr('data-imgid');
            let selected = false;
            for(var i=0;i<_this.selected.length;i++){
                if(_this.selected[i].imgId == imgId){
                    selected =true;
                    break;
                }
            }
            if(selected){
                if(!$(this).find('.pb-filebox-li-imgbox-okbtn').hasClass('selected')){
                    $(this).find('.pb-filebox-li-imgbox-okbtn').addClass('selected');
                }
            }else{
                if($(this).find('.pb-filebox-li-imgbox-okbtn').hasClass('selected')){
                    $(this).find('.pb-filebox-li-imgbox-okbtn').removeClass('selected');
                }
            }
        })
    }
    _showSelectNumb(){
        $(".pb-filebox-shadow .pb-filebox-foot-left-text-numb").text(this.selected.length+' / '+this.option.max_select_count+' 共'+this.imgcount );

        if(this.selected.length==0){
            $('.pb-filebox-shadow .btn1-ok,.pb-filebox-shadow .btn1-del').prop('disabled',true);
        }else{
            $('.pb-filebox-shadow .btn1-ok,.pb-filebox-shadow .btn1-del').prop('disabled',false);
        }

        $('.pb-filebox-shadow .pb-filebox-pageinfo').text(this.imgcount+'条 第'+this.pagenumb+'/'+this.pagecount+'页');
        if(this.pagenumb<=1 ){
            $('.pb-filebox-shadow .btn1-page-prev').prop('disabled',true);
        }else{
            $('.pb-filebox-shadow .btn1-page-prev').prop('disabled',false);
        }

        if(this.pagecount>1 && this.pagecount>this.pagenumb){
            $('.pb-filebox-shadow .btn1-page-next').prop('disabled',false);
        }else{
            $('.pb-filebox-shadow .btn1-page-next').prop('disabled',true);
        }
    }
    _refreshImgBoxWidth(){
        let ulwidth = $('.pb-filebox-shadow .pb-filebox-ul-imgs').innerWidth() - 2*this.ulpadding2 ;
        var _liwidth = parseInt(ulwidth/parseInt(ulwidth/this.liwidth+1));
        $('.pb-filebox-shadow .pb-filebox-li-img').width(_liwidth);
    }
    _loadImgs(){
        if(this.option.load_url ==null || this.option.load_url == '' ){
            alert('参数load_url不允许为空');
            return;
        }

        let _this = this;

        let ajaxOpt ={};
        ajaxOpt.type = this.option.method;
        ajaxOpt.url = this.option.load_url;
        ajaxOpt.dataType = 'json';
        ajaxOpt.data = {pagesize: this.option.pagesize, pagenumb: this.pagenumb };

        let headers = {};
        if(this.option.headers != null){
            headers = this.option.headers;
        }
        headers.Accept="application/json; charset=utf-8";
        ajaxOpt.headers = headers;
        ajaxOpt.success=function(res){
            if(res.code ==1){
                let page = res.data;
                // 计算图片总数
                _this.imgcount = res.data.count;

                // 计算总页数
                _this.pagecount = _this.imgcount/_this.option.pagesize;
                if(_this.pagecount > parseInt(_this.pagecount)){
                    _this.pagecount = parseInt( _this.pagecount)+1;
                }

                for(var i=0;i<page.rows.length;i++){
                    var obj = page.rows[i];
                    _this.addImg(obj.imgId,obj.imgUrl,obj.imgTitle);
                }
                _this._refreshSelectStatus();
                _this._showSelectNumb();

            }else{
                alert(res.code+":"+res.msg);
            }
        }

        $.ajax(ajaxOpt);
    }
    _clearImgs(){
        jQuery('.pb-filebox-shadow li.pb-filebox-li-img').remove();
    }
    _build(){
        const headHeight = 60;
        const footHeight = 60;
        const imgBoxWidth = this.liwidth;
        const imgBoxHeight = this.liheight;
        const imgTitleHeight = 32;
        const imgBoxPadding1 = 10;
        const imgBoxPadding2 = 10;

        let _this = this;
        let html = `<div class="pb-filebox-shadow"> <div class="pb-filebox"> 
 <div class="pb-filebox-head"> <h3 class="pb-filebox-title"> 选择服务器文件 </h3> </div>
 <div class="pb-filebox-body"> <div class="pb-filebox-imgs">
 <ul class="pb-filebox-ul-imgs">
  
  <li class="pb-cl"></li>
</ul>
</div> </div>
 <div class="pb-filebox-foot">

    <div class="pb-filebox-foot-btns">
    <button type="button" class="btn1 btn1-success btn1-upload">本地上传</button>
    <button type="button" class="btn1 btn1-success btn1-del" disabled="disabled">删除图片</button> &nbsp;&nbsp;
    <button type="button" class="btn1 btn1-success btn1-ok" disabled="disabled">选中图片</button>
    <button type="button" class="btn1 btn1-cancel"> 取  消 </button>
    </div>
    <div class="pb-filebox-foot-pages">
    已选 <span class="pb-filebox-foot-left-text-numb">0</span> 张图片  
    <button type="button" class="btn1 btn1-page btn1-page-prev" disabled="disabled">上一页</button>
    <span class="pb-filebox-pageinfo">0条 / 0页</span>
    <button type="button" class="btn1 btn1-page btn1-page-next">下一页</button>
    </div>
  </div>
 </div> </div>
<style type="text/css">
.pb-filebox-shadow,pb-filebox-shadow  *{
    box-sizing: border-box;
}
.pb-filebox-shadow{
    position: fixed;
    z-index: 1300;
    left: 0px;
    right: 0px;
    top: 0px;
    bottom: 0px;
    background-color: rgba(0,0,0,0.3);
}
.pb-filebox-shadow .pb-filebox{
    position: absolute;
    width: 70%;
    top: 100px;
    left: 50%;
    margin-left: -35%;
    height: 70%;
    background-color: #FFF;
    box-shadow: 0 1px 6px rgba(0,0,0,0.3);
    border-radius: 3px;
}
.pb-filebox-shadow .pb-filebox-head{
    position: absolute;
    height:  ${headHeight}px;
    width: 100%;
    top: 0px;
}
.pb-filebox-shadow .pb-filebox-head .pb-filebox-title{
    position: absolute;
    padding-top: 20px;
    padding-left: 40px;
    font-size: 16px;
            
}
.pb-filebox-shadow .pb-filebox-body{
    position: absolute;
    z-index: 1310;
    top: ${headHeight}px;
    bottom: ${footHeight + 20}px;
    width: 100%;
    overflow-y: auto;
 }

 .pb-filebox-shadow .pb-filebox-body .pb-filebox-ul-imgs{
    padding: 10px ${this.ulpadding2}px;
    margin: 0px;
 }
 .pb-filebox-shadow .pb-filebox-body li{
    margin: 0px;
    padding: 0px;
    list-style: none;
 }
 .pb-filebox-shadow .pb-filebox-body .pb-filebox-li-img{
    float: left;
    position: relative;
    width: ${imgBoxWidth}px;
    height: ${imgBoxHeight}px;
    padding: ${imgBoxPadding1}px ${imgBoxPadding2}px;
 }
.pb-filebox-shadow .pb-filebox-body .pb-filebox-imgbox{
    height: ${imgBoxHeight - 2*imgBoxPadding1 - imgTitleHeight }px;
    border-left: solid 1px #e3e3e3;
    border-right: solid 1px #e3e3e3;
    border-top: solid 1px #e3e3e3;
}
.pb-filebox-shadow .pb-filebox-body .pb-filebox-img-item{
    width: 100%;
    height: 100%;
    object-fit: cover;
}
.pb-filebox-shadow .pb-filebox-body .pb-filebox-imgtitle{
    height: ${imgTitleHeight}px;
    border-left: solid 1px #e3e3e3;
    border-right: solid 1px #e3e3e3;
    border-bottom: solid 1px #e3e3e3;
    padding-left: 5px;
    padding-right: 5px;
}
.pb-filebox-shadow .pb-filebox-body .pb-filebox-li-imgbox-okbtn.selected{
    display: block;
}
.pb-filebox-shadow .pb-filebox-body .pb-filebox-li-imgbox-okbtn{
    position: absolute;
    display:none;
    z-index : 1402;
    left: ${imgBoxPadding2}px;
    right: ${imgBoxPadding2}px;
    top: ${imgBoxPadding1}px;
    bottom: ${imgBoxPadding2+imgTitleHeight}px;
    background-color: RGBA(0,0,0,0.5);
    
}
.pb-filebox-shadow .pb-filebox-body .pb-filebox-li-imgbox-okbtn::before{
    content: '';
    position: absolute;
    width: ${imgBoxWidth/8*2}px;
    height: ${imgBoxWidth/8*3}px;
    color: #FFF;
    border-bottom: 5px solid;
    border-right: 5px solid;
    left: 50%;
    top: 30%;
    transform-origin: center;
    transform: translate(-50%, -30%) rotate(45deg);
    -webkit-transform: translate(-50%, -30%) rotate(45deg);
}
.pb-filebox-shadow .pb-filebox-body .pb-filebox-imgtitle-text{
    font-size: 12px;
    line-height: 32px;
    white-space: nowrap;
    overflow: hidden;
     text-overflow: ellipsis;
}
.pb-filebox-shadow .pb-filebox-foot{
    position: absolute;
    display: flex;
    z-index: 1310;
    text-align: center;
    bottom: 0px;
    width: 100%;
    height: ${footHeight}px;
}

.pb-filebox-shadow .pb-filebox-foot-btns{
    width: 50%;
    padding-left: 20px;
    
}

.pb-filebox-shadow .pb-filebox-foot-pages{
    width: 50%;
    text-align: right;;
    padding-right: 20px;
}

.pb-filebox-shadow .btn1{
    outline: 0px;
    height: 32px;
    padding:0px 12px;
    border: 0px;
    line-height: 32px;
    text-align: center;
    font-size: 14px;
    border-radius: 3px;
    cursor: pointer;
}
.pb-filebox-shadow .pb-filebox .btn1:hover{
    outline: 0px;
}
.pb-filebox-shadow .btn1-upload{
    display: none;
}
.pb-filebox-shadow .btn1-success{
    background-color: #44b549;
    color: #FFF;
    font-weight: bold;
}
.pb-filebox-shadow .pb-filebox .btn1-success:not(disabled):hover{
    background-color: #1AAD19;
    color: #e4e4e4;
}
.pb-filebox-shadow .pb-filebox .btn1-success:not(disabled):active{
    background-color: #44b549;
    color: #FFF;
}

.pb-filebox-shadow .btn1-success:disabled{
    font-weight: bold;
    background-color: #e4e4e4;
    color: #a5a6aa;
}
.pb-filebox-shadow .btn1-page:disabled,.pb-filebox-shadow .btn1-page:disabled:hover{
    font-weight: bold;
    background-color: #e4e4e4;
    color: #a5a6aa;
}
.pb-filebox-shadow .btn1-page:not(disabled){
    background-color: #f0ad4e;
    color: #fff;
}
.pb-filebox-shadow .btn1-page:not(disabled):hover{
    background-color: #f0ad6e;
    color: #e4e4e4;
}

.pb-filebox-shadow .pb-filebox .btn1-success:disabled:hover{
    background-color: #e4e4e4;
    color: #a5a6aa;
}
.pb-cl{clear:both}

</style> `;

        if($('.pb-filebox-shadow')[0]==null){
            jQuery(document).children().append(html);
        }else{
            _this._clearImgs();
        }
    }

    // 绑定事件
    _bindEvent(){
        let _this = this;
        // 当点击阴影的时候
        $('.pb-filebox-shadow').off('click');
        if(_this.option.shadowClose){
            $('.pb-filebox-shadow').on('click',function(){
                _this.hide();
            });
        }

        // 当点击pb-filebox 的冒泡
        $('.pb-filebox-shadow .pb-filebox').off('click').on('click',function (e) {
            e.stopPropagation();
        })

        // 当点击上传按钮的时候
        $('.pb-filebox-shadow .btn1-upload').off('click').on('click',function (e) {
            console.log('Hello2');
        })
        $('.pb-filebox-shadow .btn1-ok').off('click').on('click',function (e) {

            if(_this.option.onselect ==null || typeof(_this.option.onselect) != 'function'){
                alert('参数onselect不允许为空，并且必须为函数。');
                return;
            }

            if(_this.selected.length==0){
                alert('至少要选中 一个文件。')
                return;
            }

            _this.option.onselect(_this.selected);
            _this.selected = [];
            _this.hide();
        })
        $('.pb-filebox-shadow .btn1-del').off('click').on('click',function (e) {
            if(_this.option.del_url ==null  || _this.option.del_url == '' ){
                alert("del_url不允许为空");
                return;
            }

            if(!confirm('您确信要删除选中图片？')){
                return;
            }

            // 获取要删除的id
            let  imgid = '';
            for(var i=0;i<_this.selected.length;i++){
                imgid += _this.selected[i].imgId+',';
            }

            let ajaxOpt ={};
            ajaxOpt.type = _this.option.method;
            ajaxOpt.url = _this.option.del_url;
            ajaxOpt.dataType = 'json';
            ajaxOpt.data = {id: imgid };

            let headers = {};
            if(_this.option.headers != null){
                headers = _this.option.headers;
            }
            headers.Accept="application/json; charset=utf-8";
            ajaxOpt.headers = headers;
            ajaxOpt.success=function(res){
                if(res.code==1){
                    _this._clearImgs();
                    _this._loadImgs();
                }else{
                    alert('由于未知原因，删除文件失败了。');
                }
            }

            $.ajax(ajaxOpt);
        })
        // 当点击取消按钮
        $('.pb-filebox-shadow .btn1-cancel').off('click').on('click',function (e) {
            _this.selected = [];
            _this.pagenumb = 1;
            _this.hide();
        })

        $('.pb-filebox-shadow .btn1-page-prev').off('click').on('click',function (e) {
            if(_this.pagenumb >1){
                _this.pagenumb--;
            }
            _this._clearImgs();
            _this._loadImgs();
        })
        $('.pb-filebox-shadow .btn1-page-next').off('click').on('click',function (e) {
            if(_this.pagenumb < _this.pagecount){
                _this.pagenumb++;
            }
            _this._clearImgs();
            _this._loadImgs();
        })
    }
}
